<template>
	<el-drawer 
		size="70%" 
		v-model="drawer" 
		direction="rtl" 
		destroy-on-close 
		:before-close="handleClose" 
		:title="drawerTitle"
		@close="$emit('close')"
	>
    <div class="container">
			<!-- 搜索条件 -->
			<el-form :inline="true" :model="searchForm" class="search-form">
				<el-form-item label="时间周期">
					<el-select v-model="searchForm.total" clearable style="width: 230px"> <!-- 要求1：设置选择框宽度 -->
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary">搜索</el-button>
					<el-button plain @click="resetSearch">重置</el-button> <!-- 要求3：添加重置按钮 -->
				</el-form-item>
			</el-form>

			<!-- 按钮组 -->
			<div class="button-group" style="margin-bottom: 15px">
				<el-button type="primary" @click="dialogFormVisible = true">添加</el-button>
				<el-button type="danger">删除</el-button>
			</div>

			<!-- 新增对话框 -->
			<el-dialog v-model="dialogFormVisible" title="添加周期配置" width="500">
				<el-form :model="form">
					<el-form-item label="时间周期" :label-width="formLabelWidth">
						<el-select v-model="form.cycle" placeholder="请选择时间周期" style="width: 230px">
							<el-option label="1小时" value="1小时"/>
							<el-option label="4小时" value="4小时"/>
							<el-option label="12小时" value="12小时"/>
							<el-option label="24小时" value="24小时"/>
							<el-option label="1周" value="1周"/>
						</el-select>
					</el-form-item>
					<el-form-item label="收盘时间" :label-width="formLabelWidth">
						<el-select v-model="form.closingTime" placeholder="请选择收盘时间" style="width: 230px">
							<el-option label="0点" value="0点"/>
							<el-option label="8点" value="8点"/>
							<el-option label="12点" value="12点"/>
						</el-select>
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button plain @click="dialogFormVisible = false">取消</el-button>
						<el-button plain @click="handleReset">重置</el-button>
						<el-button type="primary" @click="handleConfirm">确定</el-button>
					</div>
				</template>
			</el-dialog>

			<!-- 数据表格 -->
			<el-table :data="tableData" border style="width: 100%">
				<el-table-column prop="_index" label="序号" width="70" align="center"/>
				<el-table-column prop="time" label="时间" min-width="150"/>
				<el-table-column prop="open" label="开盘价" min-width="90"/>
				<el-table-column prop="high" label="最高价" min-width="90"/>
				<el-table-column prop="low" label="最低价" min-width="90"/>
				<el-table-column prop="close" label="收盘价" min-width="90"/>
				<el-table-column prop="volume" label="成交量" min-width="90"/>
			</el-table>

			<!-- 分页 -->
			<el-pagination
				v-model:current-page="pagination.currentPage"
				v-model:page-size="pagination.pageSize"
				:total="pagination.total"
				@current-change="loadData"
				@size-change="loadData"
				layout="total, sizes, prev, pager, next, jumper"
				class="pagination"
			/>
		</div>
	</el-drawer>
</template>

<script lang="ts" setup name="subTrading">
// 新增周期映射关系
// const cycleMap = {
//   '4小时': 4,
//   '12小时': 12,
//   '24小时': 24,
//   '1周': 168
// }

// // 新增收盘时间映射
// const closingTimeMap = {
//   '0点': 0,
//   '8点': 8,
//   '12点': 12
// }

// 新增对话框相关状态
const dialogFormVisible = ref(false)
const formLabelWidth = '120px'
const form = reactive({
    cycle: '',
    closingTime: ''
})

// 新增对话框处理方法
const handleReset = () => {
    form.cycle = ''
    form.closingTime = ''
}

const handleConfirm = () => {
  if (form.cycle && form.closingTime) {
    searchForm.cycle = form.cycle // 直接使用字符串值
    searchForm.close = form.closingTime // 直接使用字符串值
	searchForm.total = searchForm.cycle + " " + searchForm.close
    dialogFormVisible.value = false
    loadData()
  }
}

// 新增标题响应式变量
const drawerTitle = ref('交易对详情');
const tradingPair = ref('');
// 数据表格相关
interface TradeData {
  time: string
  open: number
  high: number
  low: number
  close: number
  volume: number
}
const tableData = ref([]);
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});
// 搜索表单
const searchForm = reactive({
	cycle: '1小时', // 修改默认值为1小时
	close: '8点',   
	total: ''
});
import {GetList} from './api';
import { onMounted, ref, reactive, watch  } from 'vue'; 
import { useFs } from '@fast-crud/fast-crud';
import { createCrudOptions } from './crud';
import { useExpose } from '@fast-crud/fast-crud';
import { ElMessageBox, ElMessage } from 'element-plus';

const drawer = ref(false); 

// 添加交易对设置与抽屉打开的同步逻辑
const openDrawer = (title: string) => {
	setTitle(title);       
	tradingPair.value = title; 
	// 新增重置搜索条件
	searchForm.cycle = '1小时';
	searchForm.close = '8点';
	searchForm.total = ''
	drawer.value = true;   
}

// 暴露设置标题的方法
const setTitle = (title: string) => {
  drawerTitle.value = `${title}`;
}
// 添加抽屉状态监听
watch(drawer, (newVal) => {
  if (newVal && tradingPair.value) {
    loadData();
  }
});

const emit = defineEmits<{
  (e: 'close'): void
}>()

const handleClose = (done: () => void) => {
	ElMessageBox.confirm('您确定要关闭?', { 
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			done();
			emit('close'); // 关闭确认后触发事件
		})
		.catch(() => {
			// catch error
		});
};

const { crudBinding, crudRef, crudExpose, crudOptions, resetCrudOptions } = useFs({ createCrudOptions });
const { setSearchFormData, doRefresh } = crudExpose;

defineExpose({ drawer, setSearchFormData, doRefresh, openDrawer });

// 加载数据
const loadData = () => {
	// 添加防御性判断
	if (!drawer.value || !tradingPair.value) {
		return;
	}
	// 添加请求参数对象，包含分页和交易对信息
	const params = {
    pair_name: tradingPair.value,
    page: pagination.currentPage,
    limit: pagination.pageSize,
    cycle: searchForm.cycle,  // 添加转换后的周期参数
    close: searchForm.close    // 添加转换后的收盘时间参数
  }
	GetList(params)
		.then((response: any) => {
		// 修改状态码判断和数据结构解析
		if (response.code === 2000) {  // 根据实际返回状态码调整
			tableData.value = response.data.map((item: TradeData, index: number) => ({
			...item,
			_index: ((pagination.currentPage - 1) * pagination.pageSize) + index + 1
			}));
			// 更新分页总数
			pagination.total = response.total;
			// ElMessage.success(response.msg || '数据加载成功');
		} else {
			ElMessage.error(response.msg || '数据加载失败');
		}
		})
		.catch((error: any) => {
		//   console.error('请求错误:', error);  // 添加错误日志
		ElMessage.error('请求异常: ' + error.message);
		});
};

// 新增重置方法
const resetSearch = () => {
  searchForm.cycle = '1小时' // 修改重置后的默认值
  searchForm.close = '8点'  // 显式重置收盘时间
  searchForm.total = ''
  loadData() 
}

// 页面打开后获取列表数据
// onMounted(() => {
//   crudExpose.doRefresh();
// });
</script> 

<style scoped>
.container {
  padding: 20px;
}
.search-form {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>